package cn.cycleif.app.service;

import cn.cycleif.app.mapper.RevisionMapper;
import cn.cycleif.entity.Revision;
import cn.cycleif.enums.ObjectTypeEnum;
import cn.cycleif.enums.OpTypeEnum;
import cn.cycleif.enums.ResultCodeEnum;
import cn.cycleif.util.R;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date: 25/2/18-12:50
 * @Desc:
 */
@Service
@RequiredArgsConstructor
public class RevisionService extends ServiceImpl<RevisionMapper, Revision> {

  private final RevisionMapper revisionMapper;
  private final UserService    userService;

  public R<Object> getList(Integer type, Integer id) {
    ObjectTypeEnum typeEnum = ObjectTypeEnum.fromCode(type);
    if (typeEnum == null) return R.error(ResultCodeEnum.ERROR_REQUEST_FORMAT);

    LambdaQueryWrapper<Revision> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Revision::getObjectType, typeEnum);
    wrapper.eq(Revision::getObjectId, id);
    wrapper.orderByDesc(Revision::getCreateAt);

    List<Revision> revisions = revisionMapper.selectList(wrapper);
    List<Map<String, Object>> list = revisions.stream().map(v -> {
      Map<String, Object> map = new HashMap<>();
      map.put("basic", v);
      HashMap<String, Object> userInfo = userService.getUserSimpleInfo(v.getUserId(), null);
      map.put("user", userInfo);
      return map;
    }).toList();
    return R.success(list);
  }

  public void add(ObjectTypeEnum typeEnum, Integer objId, String title, String content) {
    Revision revision = new Revision();
    revision.setUserId(StpUtil.getLoginIdAsInt());
    revision.setOpType(OpTypeEnum.ADD);
    revision.setObjectType(typeEnum);
    revision.setObjectId(objId);
    revision.setTitle(title);
    revision.setContent(content);
    revisionMapper.insert(revision);
  }

  public void update(ObjectTypeEnum typeEnum, Integer objId, String title, String content, String log) {
    Revision revision = new Revision();
    revision.setUserId(StpUtil.getLoginIdAsInt());
    revision.setOpType(OpTypeEnum.UPDATE);
    revision.setObjectType(typeEnum);
    revision.setObjectId(objId);
    revision.setTitle(title);
    revision.setContent(content);
    revision.setLog(log);
    revisionMapper.insert(revision);
  }

  public void delete(ObjectTypeEnum typeEnum, Integer objId, String log) {
    Revision revision = new Revision();
    revision.setUserId(StpUtil.getLoginIdAsInt());
    revision.setOpType(OpTypeEnum.DELETE);
    revision.setObjectType(typeEnum);
    revision.setObjectId(objId);
    revision.setLog(log);
    revisionMapper.insert(revision);
  }
}
